package com.lz.helper.idcard

import java.io.*

//总开关
private const val file_path_hub = "/sys/class/usb_pwr_gpio/usb_pwr_on/hub_pwr_on"

//读卡器开关相关文件路径
private const val file_path_id_card = "/sys/class/usb_pwr_gpio/usb_pwr_on/id_pwr_on"

//指纹开关相关文件路径
private const val file_path_finger = "/sys/class/usb_pwr_gpio/usb_pwr_on/fp_pwr_on"

fun isHubOpen(): Boolean = readFileValue(file_path_hub) == 1

fun openHub() {
    writeFileValue(file_path_hub, "1".toByteArray())
    writeFileValue(file_path_id_card, "1".toByteArray())
    writeFileValue(file_path_finger, "1".toByteArray())
}

fun closeHub() {
    if (isHubOpen()) writeFileValue(file_path_hub, "0".toByteArray())
}

fun isCardOpen(): Boolean = readFileValue(file_path_id_card) == 1

fun openCard() {
    writeFileValue(file_path_id_card, "1".toByteArray())
}

fun isFingerOpened(): Boolean = readFileValue(file_path_finger) == 1

fun openFinger() {
    writeFileValue(file_path_finger, "1".toByteArray())
}

fun readFileValue(path: String): Int = File(path).takeIf { it.exists() }?.run {
    try {
        FileInputStream(this).use { String(readInputBuffer(it)).trim().toIntOrNull() }
    } catch (_: Exception) {
        null
    }
} ?: -1

fun readInputBuffer(input: InputStream): ByteArray = ByteArrayOutputStream().use {
    val buffer = ByteArray(1024)
    var readLen: Int
    while (true) {
        readLen = input.read(buffer)
        if (readLen == -1) break
        it.write(buffer, 0, readLen)
    }
    return it.toByteArray()
}

fun writeFileValue(path: String, value: ByteArray): Boolean = try {
    FileOutputStream(path).use { it.write(value); true }
} catch (_: Exception) {
    false
}